﻿using System;
using LBNHelpers;
using Microsoft.SPOT;
using MSH = Microsoft.SPOT.Hardware;

namespace NXTNetMF
{
	public class PSPNx3 : IDisposable
	{
		private I2CDevice Device;

		public PSPNx3(I2CBus bus, ushort address, int timeout=100)
		{
			Device = bus.CreateDevice(address, timeout);
		}

		public void Dispose()
		{
			if (Device != null)
			{
				Device.Dispose();
				Device = null;
			}
		}

		public void UpdateButtonState()
		{
			var data = new byte[6];
			try
			{
				Device.ReadPort(0x42, ref data, 1000);

			}

			// Sometime we got 0 as size transferred, dunno why, just ignore if it's the case...
			catch (I2CExecuteException ex)
			{
				if (ex.SizeTranferred != 0)
				{
					throw ex;
				}
				return;
			} 

			var b = data[0];

			LeftJoystickButton  = ((b >> 1) & 0x01) == 0;
			RightJoystickButton = ((b >> 2) & 0x01) == 0;

			D = ((b >> 4) & 0x01) == 0;
			C = ((b >> 5) & 0x01) == 0;
			B = ((b >> 6) & 0x01) == 0;
			A = ((b >> 7) & 0x01) == 0;

			b = data[1];

			L2			= ((b)      & 0x01) == 0;
			R2			= ((b >> 1) & 0x01) == 0;
			L1			= ((b >> 2) & 0x01) == 0;
			R1			= ((b >> 3) & 0x01) == 0;
			Triangle	= ((b >> 4) & 0x01) == 0;
			Circle		= ((b >> 5) & 0x01) == 0;
			Cross		= ((b >> 6) & 0x01) == 0;
			Square		= ((b >> 7) & 0x01) == 0;

			LeftJoystick  = new Point2 {X = (((float) data[2]) - 128)/128, Y = (((float) data[3]) - 128)/128};
			RightJoystick = new Point2 {X = (((float) data[4]) - 128)/128, Y = (((float) data[5]) - 128)/128};
		}

		public bool L1 { get; private set; }
		public bool L2 { get; private set; }
		public bool R1 { get; private set; }
		public bool R2 { get; private set; }
		public bool A { get; private set; }
		public bool B { get; private set; }
		public bool C { get; private set; }
		public bool D { get; private set; }
		public bool Triangle { get; private set; }
		public bool Square { get; private set; }
		public bool Circle { get; private set; }
		public bool Cross { get; private set; }

		public bool LeftJoystickButton	{ get; private set; }
		public bool RightJoystickButton { get; private set; }

		public Point2 LeftJoystick		{ get; private set; }
		public Point2 RightJoystick		{ get; private set; }
	}
}
